<template>
	<view>
		<up-navbar title="个人中心" @leftClick="leftClick" safeAreaInsetTop placeholder>
		</up-navbar>
		<up-form  labelWidth="80" labelPosition="left" :model="model1" :rules="rules"
			ref="form1">
			<up-form-item prop="userInfo.candidateImg" borderBottom ref="item1">
				<template #label>
					<up-text text="头像" size="20px" style="margin-left: 15px;"></up-text>
				</template>
				<template #right>
					<up-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxCount="1" width="70" height="70" style="margin-right: 10px;"></up-upload>
				</template>
			</up-form-item>
			<up-divider></up-divider>
			<up-form-item prop="userInfo.name" borderBottom ref="form1">
				<template #label>
					<up-col span="3">
						<up-text text="姓名" size="20px" style="margin-left: 15px;"></up-text>
					</up-col>
					<up-input placeholder="请输入姓名" font-size="20px" v-model="model1.userInfo.name"
						border="none"></up-input>
				</template>
			</up-form-item>
			<up-divider></up-divider>
			<up-form-item prop="userInfo.sex" borderBottom @click="showSex = true" ref="item1">
				<template #label>
					<up-col span="3">
						<up-text text="性别" size="20px" style="margin-left: 15px;"></up-text>
					</up-col>
				</template>
				<up-input @click="showSex = true" style="width: 200px" v-model="model1.userInfo.sex" disabled
					disabledColor="#ffffff" placeholder="请选择性别" border="none" font-size="20px"></up-input>
				<template #right>
					<up-icon name="arrow-right" style="margin-right: 20px;"></up-icon>
				</template>
				<up-action-sheet :show="showSex" :actions="actions" title="请选择性别" description="如果选择保密会报错"
					@close="showSex = false" @select="sexSelect"></up-action-sheet>
			</up-form-item>
			<up-divider></up-divider>
			<up-form-item prop="userInfo.account" borderBottom ref="form1">
				<template #label>
					<up-col span="3">
						<up-text text="手机号" size="20px" style="margin-left: 15px;"></up-text>
					</up-col>
				</template>
				<up-input placeholder="请输入手机号" font-size="20px" v-model="model1.userInfo.account"
					border="none"></up-input>
			</up-form-item>
			<up-divider></up-divider>
			<u-form-item label="年龄" prop="userInfo.age" borderBottom ref="form1" @click="dateshow = true">
				<template #label>
					<up-col span="3">
						<up-text text="年龄" size="20px" style="margin-left: 15px;"></up-text>
					</up-col>
				</template>
				<up-input @click="dateshow = true" font-size="20px" v-model="model1.userInfo.age" disabled
					disabledColor="#ffffff" placeholder="请选择出生日期" border="none"></up-input>
				<template #right>
					<up-icon name="arrow-right" style="margin-right: 20px;"></up-icon>
				</template>
				<up-datetime-picker title="请选择出生日期" v-model="birthDate" :show="dateshow" ref="datetimePicker"
					@confirm="calculateAge" @cancel="dateshow = false" mode="date" :minDate="0"
					:maxDate="Number(new Date())" :formatter="formatter"></up-datetime-picker>
			</u-form-item>
			<up-divider></up-divider>
			<up-form-item label="地址" prop="userInfo.address" borderBottom ref="form1" @click="value = true">
				<template #label>
					<up-col span="3">
						<up-text text="地址" size="20px" style="margin-left: 15px;"></up-text>
					</up-col>
				</template>
				<up-col span="10">
					<up-input @click="value = true" font-size="20px" v-model="model1.userInfo.address" disabled
						disabledColor="#ffffff" placeholder="请选择地址" border="none"></up-input>
				</up-col>
				<template #right>
					<up-icon name="arrow-right" style="margin-right: 20px;"></up-icon>
				</template>
				<city-select v-model="value" @city-change="cityChange"></city-select>
			</up-form-item>
			<up-divider></up-divider>
			<up-form-item prop="userInfo.email" borderBottom ref="form1">
				<template #label>
					<up-col span="3">
						<up-text text="邮箱" size="20px" style="margin-left: 15px;"></up-text>
					</up-col>
				</template>
				<up-input placeholder="请输入邮箱" font-size="20px" v-model="model1.userInfo.email" border="none"></up-input>
			</up-form-item>
			<up-divider></up-divider>
		</up-form>
		<view class="register">
			<up-button type="primary" size="large" text="保存" @click="submitForm"></up-button>
		</view>
		<view class="safe-area"></view>
		<up-modal :content="content" :show="show" showCancelButton closeOnClickOverlay @confirm="confirm"
			@cancel="cancel" @close="close" contentTextAlign="center"></up-modal>
	</view>
</template>

<script>
	import citySelect from '@/common/u-city-select.vue';
	export default {
		components: {
			citySelect
		},
		data() {
			return {
				model1: {
					userInfo: {
						candidateImg: '',
						name: '',
						sex: '',
						account: '',
						age: '',
						address: '',
						email: '',
					}
				},
				fileList: [], // 文件列表
				// 表单验证
				rules: {
					'userInfo.name': [{
						required: true,
						message: '请输入姓名',
						trigger: 'blur'
					}],
					'userInfo.account': [{
							required: true,
							message: '请输入手机号',
							trigger: 'blur'
						},
						{
							pattern: /^1[3-9]\d{9}$/,
							message: '请输入有效的手机号',
							trigger: 'blur'
						}
					],
					'userInfo.sex': [{
						required: true,
						message: '请选择性别',
						trigger: 'blur'
					}],
					'userInfo.email': [{
							required: true,
							message: '请输入邮箱',
							trigger: 'blur'
						},
						{
							type: 'email',
							message: '请输入有效的邮箱地址',
							trigger: 'blur'
						}
					],
					'userInfo.address': [{
						required: true,
						message: '请选择地址',
						trigger: 'blur'
					}],
				},
				// 性别
				actions: [{
						name: '男'
					},
					{
						name: '女'
					},
					{
						name: '保密'
					}
				],
				ageshow: false, // 
				//性别选择
				showSex: false,
				dateshow: false, // 日期显示
				birthDate: Number(new Date()), // 出生日期
				value: false, // 城市选择显示
				height: 30, // 城市选择高度
				bgColor: this.$u.color.bgColor, // 背景颜色
				marginTop: 30, // 顶部间隔
				marginBottom: 30, // 底部间隔
				show: false, //退出时弹窗
				content: '是否要保存再返回？'
			}
		},
		methods: {
			//导航栏点击左侧返回
			leftClick() {
				this.show = true;
			},
			// 删除图片
			deletePic(event) {
				console.log(this.fileList);
				this.fileList.splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				console.log(event)
				let lists = [].concat(event.file);
				let fileListLen = this.fileList.length;
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this.fileList[fileListLen];
					this.fileList.splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						})
					);
					fileListLen++;
				}
			},
			// 上传图片
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'api/recruit-fileUpload/files/upload',
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							if (res.statusCode === 200) {
								resolve(res.data);
								this.model1.userInfo.candidateImg = res.data;
							} else {
								reject(`上传失败，状态码：${res.statusCode}`);
							}
						},
						fail: (err) => {
							reject(`上传失败，错误信息：${err.errMsg}`);
						}
					});
				});
			},
			// 选择性别
			sexSelect(e) {
				this.model1.userInfo.sex = e.name;
				this.$refs.form1.validateField('userInfo.sex');
				this.showSex = false;
			},
			// 计算年龄
			calculateAge(date) {
				const birthDate = new Date(date.value);
				const today = new Date();
				let age = today.getFullYear() - birthDate.getFullYear();
				const monthDiff = today.getMonth() - birthDate.getMonth();
				if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
					age--;
				}
				this.model1.userInfo.age = age;
				this.dateshow = false;
			},
			// 格式化日期
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`;
				}
				if (type === 'month') {
					return `${value}月`;
				}
				if (type === 'day') {
					return `${value}日`;
				}
				return value;
			},
			// 选择地址
			cityChange(e) {
				this.model1.userInfo.address = e.province.label + '-' + e.city.label + '-' + e.area.label;
			},
			close() {
				this.show = false
				// console.log('close');
			},
			//获取用户个人信息
			getUserMessage() {
				this.$api.getCandidateMessage({
					candidateId: 1
				}).then((res) => {
					this.model1.userInfo = res.data;
					let imgurl = `../../static/${this.model1.userInfo.candidateImg}`
					this.fileList.push({url:imgurl})
				})
			},
			//直接返回
			cancel() {
				uni.navigateTo({
					url:'/pages/personal/onlineResumeView'
				})
			},
			//返回之前判断是否要保存
			confirm() {
				this.submitForm();
			},
			// 保存
			submitForm() {
				this.$refs.form1
					.validate()
					.then((res) => {
						console.log('表单验证通过');
						//保存
						this.$api.updateCandidateMessage(this.model1.userInfo).then((res) => {
							uni.showToast({
								title: `${res.code === 200 ? '保存成功' : '保存失败'}`,
								icon: 'none'
							});
							uni.navigateTo({
								url: "/pages/personal/onlineResumeView"
							});
						});
					})
					.catch((error) => {
						console.log('表单验证失败');
						this.show = false
						return false;
					});
			}
		},
		created(){
			this.getUserMessage();
		}
	}
</script>

<style>
	.safe-area {
		padding-bottom: calc(env(safe-area-inset-bottom) + 60px);
	}

	.register {
		position: fixed;
		bottom: 0;
		width: 95%;
		background-color: #fff;
		padding: 10px;
		box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
	}

	.exitBox {
		width: 250px;
		height: 200px;
		/* border: 1px solid red; */

	}
</style>